<template>
  <div :class="$style.wrap">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable></el-input>
          </el-form-item>
          <el-form-item prop="customerPhone" label="客户电话">
            <el-input v-model.trim="formData.customerPhone" number placeholder="请输入客户电话" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item prop="mscCode" label="MSC客户编码">
            <el-input v-model.trim="formData.mscCode" placeholder="请输入MSC客户编码" clearable></el-input>
          </el-form-item>
          <el-form-item prop="mscName" label="MSC客户名称">
            <el-input v-model="formData.mscName" placeholder="请输入MSC客户名称" clearable></el-input>
          </el-form-item> -->
          <el-form-item prop="customerLevel" label="客户级别">
            <CustomDictSelect
              placeholder="请选择客户级别"
              dict-type-code="KQ_CUSTOMER_LEVEL"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="formData.customerLevel"
              clearable
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="birthday" label="客户生日">
            <CalendarPickerPane v-model="formData.birthday" :type.sync="formData.birthdayType" placeholder="请选择客户生日"></CalendarPickerPane>
          </el-form-item>
          <el-form-item prop="weddingDay" label="结婚纪念日">
            <CalendarPickerPane v-model="formData.weddingDay" :type.sync="formData.weddingDayType" placeholder="请选择结婚纪念日"></CalendarPickerPane>
          </el-form-item>
          <el-form-item prop="spouseBirthday" label="配偶生日">
            <CalendarPickerPane v-model="formData.spouseBirthday" :type.sync="formData.spouseBirthdayType" placeholder="请选择配偶生日"></CalendarPickerPane>
          </el-form-item>
          <el-form-item prop="status" label="客情启用状态">
            <el-select v-model="formData.status" placeholder="请选择客情启用状态" clearable filterable>
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="handler" label="分配坐席">
            <StaffSearch v-model="formData.handler" :name.sync="formData.handlerName" placeholder="请选择分配坐席" clearable></StaffSearch>
          </el-form-item>
          <el-form-item>
            <Button @click="resetForm">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <Title title="生成关怀任务内容" :title-class="$style.title" style="padding-top:10px"></Title>
      <FormContainer :column="1">
        <el-form ref="formTask" :model="formTaskData" :rules="formTaskRules" label-width="90px" style="margin-bottom:-10px">
          <el-form-item prop="careMonth" label="关怀月份" :span="6">
            <el-date-picker v-model="formTaskData.careMonth" type="month" operator="<" :limite="getCurrentMonth()" placeholder="选择关怀月份" clearable></el-date-picker>
          </el-form-item>
          <el-form-item prop="careItems" :span="12">
            <el-checkbox-group v-model="formTaskData.careItems">
              <!-- 1生日2结婚纪念日3配偶生日 -->
              <el-checkbox :label="1">客户生日</el-checkbox>
              <el-checkbox :label="2">结婚纪念日</el-checkbox>
              <el-checkbox :label="3">配偶生日</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :span="6">
            <div class="button-container" style="padding-top:0">
              <Button type="primary" @click="genTaskHandle">生成任务</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
      <table-box ref="table" no-request :other-filters="otherFilters" :table-config="tableConfig" :other-raw="otherRaw" @selection-change="selectionChange">
        <el-table-column slot="before" type="selection" width="50" align="center" />
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import CalendarPickerPane from '@/components/CalendarPickerPane'
import StaffSearch from '@/components/StaffSearch'
import Title from '@/components/Title'
import CustomDictSelect from '@/components/CustomDictSelect'
import { filtersRaw, date2Str, deepCopy, parseTime } from '@/utils'
import { postDealerCareTask } from '@/api/guestCare'
export default {
  name: 'AddMerchant',
  components: {
    ContentWrap,
    FormContainer,
    CalendarPickerPane,
    StaffSearch,
    Title,
    CustomDictSelect
  },
  data() {
    const validatorCareMoth = (r, v, c) => {
      const m = new Date().getMonth()
      if (v.getMonth() >= m) {
        c()
      } else {
        c(new Error('关怀月份不能小于当前月份'))
      }
    }
    const validatorCareMItems = (r, v, c) => {
      if (v && v.length > 0) {
        c()
      } else {
        c(new Error('请选择关怀项目'))
      }
    }
    return {
      formData: {
        customerName: '',
        customerPhone: '',
        mscCode: '',
        mscName: '',
        customerLevel: '',
        birthday: '',
        weddingDay: '',
        spouseBirthday: '',
        status: '',
        handler: ''
      },
      formRules: {},
      // 任务
      formTaskData: {
        careMonth: '',
        careItems: []
      },
      formTaskRules: {
        careMonth: [
          { required: true, type: 'date', message: '请选择关怀月份', trigger: 'change' },
          { required: true, validator: validatorCareMoth, trigger: 'change' }
        ],
        careItems: [
          { required: true, type: 'array', message: '请选择关怀项目', trigger: 'change' },
          { required: true, validator: validatorCareMItems, trigger: 'change' }
        ]
      },
      // table-box
      selected: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/careCustomerInfo/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'createTime',
        order: 'desc',
        setting: [
          {
            prop: 'index',
            label: '序号',
            width: 80,
            align: 'center',
            formatData: (val) => {
              return val.keyIndex + 1
            }
          },
          {
            label: '经销商法人',
            width: '120',
            prop: 'legalPerson',
            isButton: true,
            clickFun: this.toDetail
          },
          {
            label: 'MSC客户编码',
            width: '120',
            prop: 'mscCustomerCode'
          },
          {
            label: 'MSC客户名称',
            width: '120',
            prop: 'mscCustomerName'
          },
          {
            label: '客户姓名',
            width: '120',
            prop: 'customerName'
          },
          {
            label: '客户电话',
            width: '120',
            prop: 'customerPhone'
          },
          {
            label: '客户级别',
            width: '120',
            prop: 'customerLevelName'
          },
          {
            label: '客户生日',
            width: '120',
            prop: 'birthday'
          },
          {
            label: '客户生日类型',
            width: '160',
            prop: 'birthdayType',
            formatData: v => this.getDateName(v.birthdayType)
          },
          {
            label: '结婚纪念日',
            width: '120',
            prop: 'weddingDay'
          },
          {
            label: '结婚纪念日类型',
            width: '160',
            prop: 'weddingDayType',
            formatData: v => this.getDateName(v.weddingDayType)
          },
          {
            label: '配偶生日',
            width: '120',
            prop: 'spouseBirthday'
          },
          {
            label: '配偶生日类型',
            width: '160',
            prop: 'spouseBirthdayType',
            formatData: v => this.getDateName(v.spouseBirthdayType)
          }

        ]
      },
      otherFilters: [],
      otherRaw: {}
    }
  },
  methods: {
    resetForm() {
      this.$refs.form.resetFields()
    },
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        const otherFilters = []
        const otherRaw = {}
        const equal = ['customerPhone', 'customerLevel', 'birthday', 'birthdayType',
          'weddingDay', 'weddingDayType', 'spouseBirthday', 'spouseBirthdayType',
          'handler', 'status']
        const birthday = ['birthday', 'weddingDay', 'spouseBirthday']
        const birthdayType = ['birthdayType', 'weddingDayType', 'spouseBirthdayType']
        const inner = []
        for (const key of Object.keys(this.formData)) {
          let v = this.formData[key]
          if (v === '' || v === undefined || v === null) {
            continue
          }
          // if (key === 'officeCode' && v) {
          //   otherRaw.officeCode = v
          //   continue
          // }
          // if (key === 'maintainState') {
          //   if (v === 1) {
          //     otherFilters.push(filtersRaw('id', '', 'not null'))
          //   } else {
          //     otherFilters.push(filtersRaw('id', '', 'is null'))
          //   }
          //   continue
          // }
          // 生日、纪念日处理
          if (birthday.includes(key)) {
            const ty = this.formData[`${key}Type`]
            if (ty === 1 || ty === 'solar') {
              v = date2Str(v, 'solar')
            } else {
              v = date2Str(v, 'lunar')
            }
            otherFilters.push(filtersRaw(key, v, '='))
            continue
          }
          if (birthdayType.includes(key)) {
            if (v === 'solar') {
              v = 1
            } else {
              v = 2
            }
            otherFilters.push(filtersRaw(key, v, '='))
            continue
          }

          if (equal.includes(key)) {
            otherFilters.push(filtersRaw(key, v, '='))
          } else if (inner.includes(key)) {
            if (v instanceof Array) {
              v = `[${v.join(',')}]`
            } else {
              v = `[${v}]`
            }
            otherFilters.push(filtersRaw(key, v, 'in'))
          } else {
            otherFilters.push(filtersRaw(key, v, 'like'))
          }
        }
        this.otherFilters = otherFilters
        this.otherRaw = otherRaw
        if (type === 'export') {
          return otherFilters
        } else {
          this.refreshTable()
        }
      })
    },
    // 刷新数据
    refreshTable(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    // 选择数据
    selectionChange(v) {
      this.selected = v
    },
    // 生成任务
    genTaskHandle() {
      return this.$refs.formTask.validate().then(() => {
        if (this.selected.length < 1) {
          this.$message.info('请选择一条数据')
          return
        }
        if (this.selected.some(e => e.status !== 1 && e.status !== '1')) {
          this.$message.info('选中的数据有客情启用状态为禁用状态，不能生成任务！')
          return
        }
        if (this.selected.some(e => e.businessStatus !== 1 && e.businessStatus !== '1')) {
          this.$message.info('选中的数据有经营状态异常，不能生成任务！')
          return
        }
        const data = deepCopy(this.formTaskData)
        data.careMonth = parseTime(data.careMonth, '{y}-{m}-{d}')
        data.careCustomerInfos = this.selected
        return postDealerCareTask(data).then(res => {
          this.$message.success(`任务生成成功，共${res.data}条！`)
          this.refreshTable('onPage')
        })
      })
    },
    // 获取当月
    getCurrentMonth() {
      const c = new Date()
      return new Date(c.getFullYear(), c.getMonth() + 1, 0, 0, 0, 0)
    },
    // 获取日期类型名
    getDateName(type) {
      if (!type) {
        return ''
      }
      return type === 1 || type === '1' ? '公历' : '农历'
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
.title{
  color: rgba(0,0,0,0.85);
  font-size: 14px;
  font-weight: 700;
}
}
</style>
